<template>
  <div class="majorEquipment">
    <el-row class="h100">
      <el-col :span="6" class="h100">
        <div class="text-border">
          <div class="text-header tree-header">
            <span>{{ treeName }}</span>
            <div
              v-if="
                ['user-select', 'dept-select', 'userOnly-select'].includes(type)
              "
            >
              <el-radio-group
                v-model="outOrgName"
                size="mini"
                @change="radioChange"
              >
                <el-radio-button
                  label="全部"
                  :disabled="btnDisable == 1 || btnDisable == 0"
                ></el-radio-button>
                <el-radio-button
                  label="内部"
                  :disabled="btnDisable == 1"
                ></el-radio-button>
                <el-radio-button
                  label="外部"
                  :disabled="btnDisable == 0"
                ></el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="left">
            <customTree
              v-if="type == 'device-select'"
              ref="equipTree"
              :showTitle="false"
              :draggable="false"
              nodeKey="id"
              @handleClickTree="handleClickTree"
            ></customTree>
            <selectTree
              v-else
              :treeData="treeData"
              :defaultProps="defaultProps"
              nodeKey="id"
              ref="tree2"
              :defaultExpandKeys="defaultExpandKeys"
              @handleClickTree="handleClickTree"
            ></selectTree>
          </div>
        </div>
      </el-col>
      <el-col :span="12" class="h100">
        <div class="text-border">
          <div class="text-header">{{ title }}</div>
          <div class="search">
            <el-input
              placeholder="输入关键字过滤"
              size="mini"
              class="treeInput"
              v-model="filterText"
              suffix-icon="el-icon-search"
              clearable
            ></el-input>
          </div>
          <div class="middle">
            <!-- <list-table-new
              ref="klTable"
              v-bind="tableConfig"
              @selectChange="selectChange"
              @defaultSelection="checkedUser"
              @radioSelect="radioSelect"
            ></list-table-new>-->
            <tableList
              v-if="true"
              ref="klTable"
              v-bind="tableConfig"
              @selectChange="selectChange"
              @selectAll="selectAll"
              @defaultSelection="checkedUser"
              @radioSelect="radioSelect"
            ></tableList>
          </div>
        </div>
      </el-col>
      <el-col :span="6" class="h100">
        <div class="text-border">
          <div class="text-header">
            已选择：
            <span>{{ choseNumber() }}</span>
          </div>
          <div class="right">
            <el-row :gutter="30" style="margin-bottom: 10px" v-if="multiple">
              <el-col :span="16">
                <el-input
                  placeholder="输入关键字过滤"
                  size="mini"
                  class="treeInput"
                  v-model="choseFilter"
                  suffix-icon="el-icon-search"
                  clearable
                ></el-input>
              </el-col>
              <el-col :span="8" style="text-align: right">
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  class="clearBtn"
                  @click="clearAll"
                  >清空</el-button
                >
              </el-col>
            </el-row>
            <div class="selectList">
              <div
                v-for="(i, index) in filterData"
                :key="index"
                class="chosedSelect"
                :class="{ isActive: i.id == currentId }"
                @click="clickChosed(i)"
              >
                <span>
                  <label v-if="['user-select', 'user'].includes(type)">
                    {{ i.orgName != "" ? `${i.name}(${i.orgName})` : i.name }}
                  </label>
                  <label v-else>{{ i.name }}</label>
                  <span v-if="i.isOutOrg == 1" class="outOrg">外部</span>
                  <span v-if="i.isOutOrg == -1" class="interim">临时</span>
                </span>
                <i
                  @click="delItem(index, i)"
                  class="el-icon-circle-close select-icon-close"
                ></i>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import {
  queryOrgTree,
  queryOrgTreeAuth,
  queryUserList,
  getOrgList,
  deviceClassifyTree,
  deviceClassifyList,
} from "@/api/common";
import {
  getCommonOrgTree,
  getCommonOrgList,
  getUserDataByOrg
} from "@/api/systemManagement/userManagement.js";
import {
  locationTree,
  getLocationList,
} from "@/api/equipmentLedger/locationManage";
import { getlocationList } from "@/api/equipmentLedger/locationManage.js";
import selectTree from "./tree";
import tableList from "./tableList.vue";
import customTree from "@/components/customTree/customTree";
export default {
  props: {
    seleteSetting: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  components: { selectTree, tableList, customTree },
  data() {
    return {
      treeData: [],
      type: "",
      title: "人员",
      treeName: "组织架构",
      defaultExpandKeys: [],
      defaultProps: {
        label: "name",
        children: "children",
      },
      currentOrg: null,
      outOrg: null, //是否是外单位
      btnDisable: null,
      outOrgName: "全部",
      radio: { equipmentName: "" }, // 选中数据
      //表格数据配置
      orgCode: "",
      tableConfig: {
        radioShow: false,
        showAllSearch: true,
        showIndex: false,
        selectionShow: true,
        showFilterBtn: false,
        showCustomBtn: false,
        rowKey: "idAndOrgId",
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },
          searchArr: [],
          queryData: {
            page: 1,
            pageSize: 15,
          },
        },
        tableMethods: {
          rowClick: (row) => {
            if (!this.defaultIds.includes(row.id) && this.isDefaultJob(row)) {
              if (this.multiple) {
                let res = this.chosedData.every((item) => {
                  if (["user-select", "user"].includes(this.type)) {
                    return row.id != item.id || row.orgId != item.orgId;
                  } else {
                    return item.id != row.id;
                  }
                });
                this.selectChange(res, row);
              } else {
                this.$refs.klTable.radioSelect(row);
              }
              this.$refs.klTable.toggleRowSelection(row);
            }
          },
        },
        selectableMethod: (row, rowIndex) => {
          if (this.defaultIds.includes(row.id) || !this.isDefaultJob(row)) {
            return false;
          } else {
            return true;
          }
        },
        isDisabled: (row) => {
          if (this.defaultIds.includes(row.id) || !this.isDefaultJob(row)) {
            return true;
          } else {
            return false;
          }
        },
        actionList: [],
        column: [
          {
            label: "用户名",
            prop: "name",
          },
          {
            label: "账号",
            prop: "account",
          },
          {
            label: "所属组织",
            prop: "orgName",
          },
        ],
        tableData: [],
        paginationObj: {
          pageSizes: [15, 30, 50, 100],
        },
        totalNumber: 0,
        showPagetion: true,
        pageSmall: true,
      },
      multiple: true,
      defaultOrg: "",
      filterData: [],
      chosedData: [],
      defaultIds: [],
      defaultJobs: [],
      currentId: "",
      filterText: "",
      choseFilter: "",
    };
  },
  created() {
    this.init();
  },
  watch: {
    filterText(val) {
      this.$refs.klTable.searchData();
    },
    choseFilter(val) {
      this.filterChoseData(val);
    },
    chosedData(val) {
      this.filterChoseData(this.choseFilter);
    },
  },
  methods: {
    init() {
      let {
        type,
        chosedData,
        multiple,
        level,
        maxSelectNum,
        outOrg,
        defaultOrg,
        defaultJob,
        defaultIds,
        allowSameUser,
        permission
      } = this.seleteSetting;
      this.chosedData = chosedData || [];
      this.defaultIds = defaultIds || [];
      this.filterData = JSON.parse(JSON.stringify(this.chosedData));
      this.type = type;
      this.outOrg = outOrg === "" ? null : outOrg;
      this.btnDisable = this.outOrg;
      this.multiple = multiple;
      this.defaultOrg = defaultOrg;
      this.defaultJob = defaultJob;
      this.allowSameUser = allowSameUser ? allowSameUser : false;
      if (multiple) {
        this.$set(this.tableConfig, "selectionShow", true);
        this.$set(this.tableConfig, "radioShow", false);
      } else {
        this.$set(this.tableConfig, "selectionShow", false);
        this.$set(this.tableConfig, "radioShow", true);
      }
      this.outOrg == 1 && (this.outOrgName = "外部");
      this.outOrg == 0 && (this.outOrgName = "内部");
      if (defaultJob) {
        this.tableConfig.column.push({
          label: "岗位",
          prop: "post",
          showTooltip: true,
          formatter: (row) => {
            if (row.postUserVoList) {
              return row.postUserVoList
                .map((item) => {
                  return item.postName;
                })
                .join(", ");
            } else {
              return "-";
            }
          },
        });
      }
      if (["dept-select", "dept", "organization"].includes(this.type)) {
        this.title = "组织列表";
        let column;
        if (!level) {
          column = [{ label: "组织", prop: "name" }];
        } else if (level == "2") {
          column = [{ label: "部门", prop: "name" }];
        } else {
          column = [{ label: "单位", prop: "name" }];
        }
        this.$set(this.tableConfig, "column", column);
        this.$set(this.tableConfig, "rowKey", "id");
      } else if (this.type == "unifyUser") {
        this.title = "组织列表";
        let column = [
          { label: "名称", prop: "name" }
        ];
        this.$set(this.tableConfig, "column", column);
        this.$set(this.tableConfig, "rowKey", "id");
        this.$set(this.tableConfig, "showPagetion", false);
        
      } else if (["location-select", "location"].includes(this.type)) {
        this.treeName = "位置树";
        this.title = "位置列表";
        let column = [
          { label: "位置名称", prop: "name" },
          { label: "上级位置", prop: "parentName" },
        ];
        this.$set(this.tableConfig, "column", column);
        this.$set(this.tableConfig, "rowKey", "id");
      } else if (
        ["deviceClassify-select", "deviceClassify"].includes(this.type)
      ) {
        this.treeName = "设备分类";
        this.title = "分类列表";
        let column = [
          { label: "名称", prop: "name" },
          { label: "上级位置", prop: "parentName" },
        ];
        this.$set(this.tableConfig, "column", column);
        this.$set(this.tableConfig, "rowKey", "id");
      } else if (["userOnly-select", "userOnly"].includes(this.type)) {
        let column = [
          {
            label: "用户名",
            prop: "name",
          },
          {
            label: "账号",
            prop: "account",
          },
          {
            label: "所属组织",
            prop: "orgVoList",
            showTooltip: true,
            formatter: (row) => {
              if (row.orgVoList) {
                return row.orgVoList
                  .map((item) => {
                    return item.name;
                  })
                  .join(", ");
              } else {
                return "-";
              }
            },
          },
        ];
        this.$set(this.tableConfig, "column", column);
        this.$set(this.tableConfig, "rowKey", "id");
      }
      this.getTreeInfo();
    },
    //点击切换内外组织
    radioChange(val) {
      if (val == "内部") {
        this.outOrg = 0;
      } else if (val == "外部") {
        this.outOrg = 1;
      } else {
        this.outOrg = null;
      }
      this.getTreeInfo();
    },
    //获取公司组织树信息
    getTreeInfo() {
      if (["location-select", "location"].includes(this.type)) {
        locationTree({ status: "enabled" }).then((res) => {
          let data = res.data;
          this.$refs.tree2.setTreeData(data);
          if (this.defaultOrg != "") {
            this.$refs.tree2.setCurrentKey(this.defaultOrg);
            this.orgCode = this.defaultOrg;
            this.$refs.klTable.searchData();
          }
        });
      } else if (this.type == "deviceClassify") {
        deviceClassifyTree().then((res) => {
          let data = res.data;
          this.$refs.tree2.setTreeData(data);
          if (this.defaultOrg != "") {
            this.$refs.tree2.setCurrentKey(this.defaultOrg);
            this.orgCode = this.defaultOrg;
            this.$refs.klTable.searchData();
          }
        });
      } else if (this.type == "unifyUser") {
        let form = {
          outOrg: this.outOrg, //是否是外单位
          permission: this.seleteSetting.permission,
        };
        queryOrgTree(form).then((res) => {
          let data = res.data;
          this.$refs.tree2.setTreeData(data);
        });
      } else {
        let form = {
          outOrg: this.outOrg, //是否是外单位
          permission: this.seleteSetting.permission,
        };
        queryOrgTree(form).then((res) => {
          let data = res.data;
          this.$refs.tree2.setTreeData(data);
          if (this.defaultOrg != "") {
            this.$refs.tree2.setCurrentKey(this.defaultOrg);
            this.orgCode = this.defaultOrg;
            this.$refs.klTable.searchData();
          }else{
            let currentOrg = this.$store.getters.currentInfo.currOrg;
            this.$refs.tree2.setCurrentKey(currentOrg);
            this.orgCode = currentOrg;
            this.$refs.klTable.searchData();
          }
        });
      }
    },
    //点击树
    handleClickTree(node) {
      this.orgCode = node.id;
      this.$refs.klTable.searchData();
    },
    //获取表格数据
    getTableData(params, sortStr) {
      let queryData = Object.assign({}, params);
      if (sortStr.length > 0) {
        queryData.orders = sortStr;
      }
      if (["user-select", "user"].includes(this.type)) {
        queryData.orgId = this.orgCode;
        queryData.name = this.filterText;
        queryData.nameBy = this.filterText;
        queryData.isOutOrg = this.outOrg;
        queryData.permission = true;
        queryUserList(queryData).then((res) => {
          res.data.forEach((item) => {
            item.idAndOrgId = item.id + item.orgId;
          });
          this.$set(this.tableConfig, "tableData", res.data);
          this.$set(this.tableConfig, "totalNumber", res.total);
          this.setDefaultRadio();
        });
      } else if (["userOnly-select", "userOnly"].includes(this.type)) {
        queryData.orgId = this.orgCode;
        queryData.name = this.filterText;
        queryData.nameBy = this.filterText;
        queryData.isOutOrg = this.outOrg;
        getUserDataByOrg(queryData).then((res) => {
          this.$set(this.tableConfig, "tableData", res.data);
          this.$set(this.tableConfig, "totalNumber", res.total);
          this.setDefaultRadio();
        });
      } else if (["dept-select", "dept", "organization"].includes(this.type)) {
        queryData.levelPath = this.orgCode;
        queryData.name = this.filterText;
        queryData.level = this.seleteSetting.level;
        queryData.outOrg = this.outOrg;
        queryData.permission = this.seleteSetting.permission;
        getOrgList(queryData).then((res) => {
          let data = JSON.parse(JSON.stringify(res.data));
          data.forEach((child) => {
            if (!this.defaultIds.includes(child.id)) {
              child.disabled = false;
            } else {
              child.disabled = true;
            }
          });
          this.$set(this.tableConfig, "tableData", data);
          this.$set(this.tableConfig, "totalNumber", res.total);
          this.setDefaultRadio();
        });
      }else if(this.type == "unifyUser"){
        queryData.parentCode = this.orgCode;
        queryData.name = this.filterText;
        getCommonOrgList(queryData).then((res) => {
          let data = JSON.parse(JSON.stringify(res.data));
          this.$set(this.tableConfig, "tableData", data);
          this.setDefaultRadio();
        });
      } else if (["location-select", "location"].includes(this.type)) {
        queryData.parentIdLike = this.orgCode;
        queryData.name = this.filterText;
        queryData.status = "enabled";
        getlocationList(queryData).then((res) => {
          this.$set(this.tableConfig, "tableData", res.data.list);
          this.$set(this.tableConfig, "totalNumber", res.data.total);
          this.setDefaultRadio();
        });
      } else {
        queryData.id = this.orgCode;
        queryData.name = this.filterText;
        deviceClassifyList(queryData).then((res) => {
          this.$set(this.tableConfig, "tableData", res.data.records);
          this.$set(this.tableConfig, "totalNumber", res.data.total);
          this.setDefaultRadio();
        });
      }
    },
    //
    isDefaultJob(row) {
      if (
        ["user-select", "user"].includes(this.type) &&
        this.defaultJob &&
        row.isOutOrg == "0"
      ) {
        let jobs = row.postUserVoList
          ? row.postUserVoList.map((item) => item.postName)
          : [];
        if (jobs.includes(this.defaultJob)) {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    },
    //默认选中第一条
    setDefaultRadio() {
      if (!this.multiple&&this.chosedData.length==0) {
        if (this.tableConfig.tableData.length > 0) {
          let row = this.tableConfig.tableData[0];
          if (this.defaultIds.includes(row.id) || !this.isDefaultJob(row)) {
            return;
          } else {
            this.radioSelect(row);
            this.checkedUser();
          }
        }
      }
    },
    //单选框选中时触发
    radioSelect(row) {
      this.chosedData = [row];
    },
    //勾选已选人员或组织
    checkedUser() {
      if (this.chosedData.length > 0) {
        if (this.multiple) {
          this.chosedData.forEach((item) => {
            this.tableConfig.tableData.forEach((value) => {
              if (this.type == "user-select") {
                let idAndOrgId = item.id + item.orgId;
                if (value.idAndOrgId == idAndOrgId) {
                  this.$refs.klTable.selectioned(value);
                }
              } else {
                if (value.id == item.id) {
                  this.$refs.klTable.selectioned(value);
                }
              }
            });
          });
        } else {
          let row = this.chosedData[0];
          row.idAndOrgId = row.id + row.orgId;
          this.$refs.klTable.radioSelect(row);
        }
      }
    },
    //添加或取消已选用户
    selectChange(selected, row) {
      if (selected) {
        let hasSame = false;
        if (this.allowSameUser) {
          this.chosedData.push(row);
        } else {
          this.chosedData.forEach((item, index) => {
            if (item.id == row.id) {
              hasSame = true;
              this.chosedData.splice(index, 1, row);
              let onceData = this.tableConfig.tableData.find((child) => {
                return child.id == item.id && child.orgId == item.orgId;
              });
              let len = this.tableConfig.tableData.filter(
                (child) => child.id == row.id
              );
              if (len.length > 1) {
                this.$refs.klTable.selectionCalce(onceData);
              }
              //
            }
          });
          if (!hasSame) {
            this.chosedData.push(row);
          }
        }
      } else {
        this.chosedData.forEach((item, i) => {
          if (item.id == row.id) {
            this.chosedData.splice(i, 1);
            return;
          }
        });
      }
    },
    //选择全部
    selectAll(list) {
      this.tableConfig.tableData.forEach((item, i) => {
        if (!this.defaultIds.includes(item.id)) {
          this.selectChange(list, item);
        }
      });
    },
    //点击移除的时候触发
    delItem(index, row) {
      if (this.multiple) {
        this.chosedData.forEach((item, i) => {
          if (row.id == item.id) {
            this.chosedData.splice(i, 1);
          }
        });
        this.tableConfig.tableData.map((item) => {
          if (item.id === row.id) {
            this.$refs.klTable.selectionCalce(item);
          }
        });
      } else {
        this.chosedData.splice(index, 1);
        this.filterData.splice(index, 1);
        this.$refs.klTable.radioClick(null);
      }
    },
    //清除所有
    clearAll() {
      this.chosedData.length = 0;
      this.filterData = [];
      this.$refs.klTable.clearSelection();
    },
    //过滤已选人员
    filterChoseData(val) {
      let reg = new RegExp(val);
      this.filterData = this.chosedData.filter((item) => {
        return item.name.match(reg);
      });
    },
    //选择人员或组织数量
    choseNumber() {
      if (["user-select", "user"].includes(this.type)) {
        return `${this.chosedData.length}人`;
      } else {
        return `${this.chosedData.length}个`;
      }
    },
    //展示
    formatter(i) {
      if (i.isOutOrg == 0) {
        return "";
      } else if (i.isOutOrg == 1) {
        return `<span class="outOrg">外部</span>`;
      } else {
        return `<span class="interim">临时</span>`;
      }
    },
    clickChosed(i) {
      this.currentId = i.id;
    },
    //返回选择的数据
    getSelectData() {
      let data = JSON.parse(JSON.stringify(this.chosedData));
      return data;
    },
  },
};
</script>
<style  lang="less" scoped>
.majorEquipment {
  height: calc(100% - 15px);
  /deep/.el-input--mini .el-input__inner {
    height: 32px;
    line-height: 32px;
  }
  .search {
    width: 40%;
    margin: 0 0 10px 10px;
  }
  .text-border {
    position: relative;
    height: 100%;
    margin: 5px;
    border: 1px #ebebeb solid;
    .text-header {
      height: 40px;
      line-height: 40px;
      padding: 0 14px;
      border-bottom: 1px #ebebeb solid;
      text-align: left;
      font-weight: 700;
      color: #666;
    }
    .tree-header {
      display: flex;
      justify-content: space-between;
    }
    .text-header:first-child {
      margin-bottom: 15px;
    }
    .left {
      height: calc(100% - 40px);
    }
    .middle {
      padding: 0 10px 10px 10px;
      height: calc(100% - 115px);
    }
    .right {
      height: calc(100% - 35px);
      padding: 0 10px;
      .selectList {
        height: calc(100% - 88px);
        overflow: auto;
        .chosedSelect {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 4px 10px;
          line-height: 23px;
        }
        .clearBtn {
          border: 1px solid #0d60b4;
          color: #0d60b4;
        }
        .isActive {
          background-color: #f8f8f8;
        }
      }
    }
    .table-input {
      width: 95% !important;
      margin: 0 auto;
      .tableInputLeft {
        float: left;
        width: 35%;
      }
      .tableInputRight {
        float: right;
        width: 60%;
      }
      .tableInputLeft,
      .tableInputRight {
        height: 30px;
        line-height: 30px;
        border-radius: 2px;
        margin-bottom: 15px;
      }
    }
    .clearF::after {
      content: "";
      display: table;
      height: 0;
      clear: both;
      visibility: hidden;
    }
    .select-text {
      float: left;
      margin-left: 10px;
      height: 20px;
      line-height: 12px;
    }
    .select-icon-close {
      float: right;
      margin-right: 10px;
    }
  }
  .outOrg {
    margin-left: 10px;
    background: rgba(250, 162, 36, 0.2);
    //color: #FAA224 ;
    opacity: 0.2;
    color: black;
    border-radius: 4px;
    padding: 1px 4px;
  }
  .interim {
    margin-left: 10px;
    background: rgba(239, 76, 76, 0.2);
    opacity: 0.2;
    border-radius: 4px;
    padding: 1px 8px;
    color: red;
  }
}
</style>